package com.example.myblog1_0.service.Impl;

import com.example.myblog1_0.mapper.LeaveMessageMapper;
import com.example.myblog1_0.model.LeaveMessage;
import com.example.myblog1_0.service.LeaveMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: xc
 * @Date: 2018/12/22 14:28
 * @Description:
 **/
@Service
public class LeaveMessageServiceImpl implements LeaveMessageService {
    @Autowired
    LeaveMessageMapper messageMapper;
    @Override
    public JSONObject saveMessage(LeaveMessage leaveMessage) {
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        leaveMessage.setSendTime(time);
        if (messageMapper.saveMessage(leaveMessage)){
            jsonObject.put("status",200);
            jsonObject.put("message","储存成功");
        }else {
            jsonObject.put("status",403);
            jsonObject.put("message","储存失败");
        }
        return jsonObject;
    }

    @Override
    public JSONObject findAllMessage(int row,int pageNum) {
        /**
         * 此行必须放在第一行，否则pageSize会出错
         */
        PageHelper.startPage(pageNum,row);

        List<LeaveMessage> messages = messageMapper.findAllMessage();


        PageInfo<LeaveMessage> pageInfo = new PageInfo<>(messages);
        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getPageSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        JSONArray result = new JSONArray();
        JSONObject jsonObject;
        for (LeaveMessage message : messages){
            jsonObject = new JSONObject();
            jsonObject.put("username",message.getUsername());
            jsonObject.put("message",message.getMessage());
            jsonObject.put("sendTime",message.getSendTime());
            jsonObject.put("avatarUrl",message.getUserAvatarUrl());
            result.add(jsonObject);
        }
        JSONObject returnJson = new JSONObject();
        returnJson.put("status",200);
        returnJson.put("result",result);
        returnJson.put("pageInfo",pageJson);

        return returnJson;
    }
}
